package com.my.job;

import com.my.service.WecomMessageSeqService;
import com.tencent.wework.Finance;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author sjx
 * @date 2025/2/24 11:54
 */
@Slf4j
@Component
public class WecomMessageTask {

    @Value("${wecom.corpId}")
    private String corpId;
    @Value("${wecom.msg.secret}")
    private String secret;
    @Autowired
    private WecomMessageSeqService wecomMessageSeqService;

    @Scheduled(cron = "0/30 * * * * ? ")
    public void pushMsg() {
        log.info("每隔30秒拉取一次聊天内容");
        long sdk = Finance.NewSdk();
        Finance.Init(sdk, corpId, secret); // 初始化

        long ret = 0;
        int seq = Math.toIntExact(wecomMessageSeqService.getSeq()); // 从指定的seq开始拉取消息，注意的是返回的消息从seq+1开始返回，seq为之前接口返回的最大seq值。首次使用请使用seq:0（这个值需要记录下来，以便下一次的拉去）
        int limit = 100;

        long slice = Finance.NewSlice();
        ret = Finance.GetChatData(sdk, seq, limit, null, null, 3, slice);
        if (ret != 0) {
            log.warn("获取的结果:{}",ret);
            return;
        }
        String getchatdata = Finance.GetContentFromSlice(slice);
        log.info("{}，拉去的聊天记录密文结果：{}",seq,getchatdata);
        JSONObject jo = new JSONObject(getchatdata);
        JSONArray chatdata = jo.getJSONArray("chatdata");
        log.info("消息数：{}",chatdata.length());

        /*for (int i = 0; i < chatdata.length(); i++) {
            JSONObject data = new JSONObject(chatdata.get(i).toString());
            String encryptRandomKey = data.getString("encrypt_random_key");
            String encryptChatMsg   = data.getString("encrypt_chat_msg");
            long msg = Finance.NewSlice();
            try {
                // 聊天记录密文解密
                String message = RSAEncrypt.decryptRSA(encryptRandomKey, PriKeyConstants.priKey);
                ret = Finance.DecryptData(sdk, message, encryptChatMsg, msg);
                if (ret != 0) {
                    System.out.println("getchatdata ret " + ret);
                    return;
                }
                String plaintext = Finance.GetContentFromSlice(msg);
                System.out.println("decrypt ret:" + ret + " msg:" + plaintext);
                Finance.FreeSlice(msg);

                JSONObject plaintextJson = new JSONObject(plaintext);
                // 拉去媒体文件解密
                String msgtype = plaintextJson.getString("msgtype");
                if ("mixed".equals(msgtype)) {
                    // 混合消息
                    JSONArray array = new JSONArray();
                    JSONObject mixed = new JSONObject(plaintextJson.get("mixed").toString());
                    JSONArray items = mixed.getJSONArray("item");
                    for (int j = 0; j < items.length(); j++) {
                        JSONObject item = new JSONObject(items.get(j).toString());
                        JSONObject content = new JSONObject(item.getString("content"));
                        String type = item.getString("type");
                        if ("text".equals(type)) {
                            item.put("content", content.getString("content"));
                        }
                        array.put(item);
                    }
                    JSONObject content = new JSONObject();
                    content.put(msgtype, array.toString());
                    plaintextJson.put(msgtype, content.toString());
                }
                // 会话内容
                log.info("获取的消息:{}",plaintextJson);
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
        }*/
        wecomMessageSeqService.upSeq((long) seq);
    }

}
